package com.kmcsoft.core.service.impl;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @version 
 * @author  Che Hoang-Cong
 * @since   KMC-ERP
 * @create on  Jul 13, 2011
 */
public class FreeMakerHelperServiceImpl {

    private static final Logger LOGGER = LoggerFactory.getLogger(FreeMakerHelperServiceImpl.class);

    public String process(final String template, final Object input) {
        final Configuration cfg = new Configuration();
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        return process(cfg, template, input);
    }

    public String process(final String template, final Map<String, Object> input) {
        return process(new Configuration(), template, input);
    }

    private String process(final Configuration cfg, final String template, final Object input) {
        String rc = null;

        try {
            final Template temp = new Template("TemporaryTemplate", new StringReader(template), cfg);

            final Writer out = new StringWriter();
            temp.process(input, out);
            rc = out.toString();
            out.close();
        } catch (final Exception e) {
            LOGGER.error("Problem", e);
        }

        return rc;
    }
}
